package core

import (
	"dgo/goutils/utils"
	"dgo/plg/plgbasev0"
	"fmt"
	"gitee.com/ymofen/supervalue"
)

type IOChanellPlugin struct {
	plgbasev0.ProjBasePlugin
	input  *plgbasev0.InnerEx
	output *plgbasev0.InnerOutput
}

/*
**

	{
	  "id":"iochannel-copy",
	  "type":"core.iochannel",
	  "conf":{
	      "input":{"id":"core-wsex", "topic":"BJ05" },
	      "output":{"id":"rtcm-disp", "topic":"BJ05"}
	   }
	}
*/
func (this *IOChanellPlugin) ReloadConf(conf *wrapper.SuperValue) error {
	if this.output == nil {
		this.output = plgbasev0.NewInnerOutput()
	}
	if this.input == nil {
		this.input = plgbasev0.NewInnerEx()
	}

	this.output.ReloadConf(conf.ValueByName("output"), nil, nil, nil)

	this.input.ReloadConf(conf.ValueByName("input"))
	conf.CheckStrFunc("input.topic", func(strv string) {
		this.input.Subscribe(strv, func(sender interface{}, channelid string, subscribeid interface{}, data interface{}, tag interface{}, isBreak *bool) bool {
			topic := this.output.OutputTopic()
			if len(topic) == 0 {
				topic = channelid
			}
			this.output.OutputData(topic, data, sender, tag)
			return true
		})
	})

	return nil
}

func (this *IOChanellPlugin) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {
		this.input.Release()
		this.ReleaseFlag = 1

	}
	return
}

func CreateCoreIOChanellPluginFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &IOChanellPlugin{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}

	rval = obj
	return
}
